package cn.wowjoy.office.materialmanage.materiallist;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;

import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.R;

import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.customview.MaskFramLayout;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.common.widget.PopuListWindow;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.response.GoodsDetailResponse;
import cn.wowjoy.office.databinding.ActivityMaterialListBinding;

import cn.wowjoy.office.materialmanage.materialdetail.MaterialDetailActivity;


public class MaterialListActivity extends NewBaseActivity<ActivityMaterialListBinding,MaterialListViewModel> {


    private PopuListWindow popuListWindow;
    private List<PopuModel> popuModels;
    private MDialog waitDialog;
    private boolean isFirst = true;
    private String isStop = "";


    public String getKey() {
        return key;
    }

    @Override
    protected void onResume() {
        super.onResume();
        openBroadCast();
    }

    @Override
    protected void onStop() {
        super.onStop();
        closeBroadCast();
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        key = msg;
        binding.searchEditText.setText(key);
        viewModel.getGoodsListInfo(isStop,msg,true);

    }



    private int initHeight;
    private boolean isOpen = false;

    private String key;

    @Override
    protected void init(Bundle savedInstanceState) {
        initData();
        initMenu();
        initMaterialRecyclerList();
        initObsever();
        viewModel.getGoodsListInfo("","",true);
    }

    private void initData(){

        binding.setViewmodel(viewModel);
        initHeight= getResources().getDimensionPixelSize(R.dimen.height2)*3;
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


    }

    private void initMenu(){
        binding.menuFl.setBgAlapht(77);
        binding.noticeRl.setVisibility(View.GONE);
        binding.meunRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.meunRecyclerview.setAdapter(viewModel.menuAdapter);
        binding.meunRecyclerview.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
        viewModel.createMeun();
        binding.menuFl.setDimissListener(new MaskFramLayout.DimissListener() {
            @Override
            public void onDismiss() {
                closeFolder();
                binding.menu.setSelected(isOpen);
            }
        });

        binding.menu.setSelected(false);
        binding.menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeErrorview();
                if (isOpen){
                    closeFolder();

                } else {
                    openFolder();
                }
                binding.menu.setSelected(isOpen);


            }
        });

    }

    protected void refreshRV(){
        binding.recyclerView.refresh();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REFRESH_CODE && null != data){
            if (data.getBooleanExtra(Constants.IS_NEED_REFRESH, false)){
               refreshRV();
            }
        }
    }

    private void initMaterialRecyclerList(){
        binding.emptyView.emptyContent.setText("可搜索物资名称，规格型号，物资分类，条形码");
        binding.recyclerView.setEmptyView(binding.emptyView.getRoot());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        binding.recyclerView.setAdapter(materialListPresenter.getViewModel().materialListAdapter);
        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
//        materialListPresenter.getViewModel().setData(true,null);
        binding.searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                hideSoftInput();
                if (isOpen){
                    closeFolder();
                }
                key = binding.searchEditText.getText().toString().trim();
                viewModel.getGoodsListInfo(isStop,key,true);

//                materialListPresenter.getInfo();
                return true;
            }
        });
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(binding.searchEditText.getText().toString())){
                    binding.delete.setVisibility(View.VISIBLE);
                } else {
                    binding.delete.setVisibility(View.GONE);
                    key = null;
                }

            }
        });
        binding.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.searchEditText.setText("");
                binding.delete.setVisibility(View.GONE);
                key = null;
            }
        });
        binding.closeNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.noticeRl.setVisibility(View.GONE);
            }
        });



    }

    private void initObsever(){
        viewModel.getGoodsListLiveData().observe(this, new Observer<LiveDataWrapper<List<GoodsDetailResponse>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<GoodsDetailResponse>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialListActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        if (isFirst) {
                            showNotice();
                            isFirst = false;
                        }
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        handleException(listLiveDataWrapper.error,true);
                        break;
                }
            }
        });

        viewModel.getGoodsDetail().observe(this, new Observer<GoodsDetailResponse>() {
            @Override
            public void onChanged(@Nullable GoodsDetailResponse response) {
                jump(response);
            }
        });
        viewModel.getStartStop().observe(this, new Observer<LiveDataWrapper<ResultEmpty>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<ResultEmpty> resultEmptyLiveDataWrapper) {
                switch (resultEmptyLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialListActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        viewModel.getGoodsListInfo(isStop,key,true);
                        refreshRV();
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        handleException(resultEmptyLiveDataWrapper.error,false);
                        break;
                }
            }
        });
        viewModel.meun.observe(this, new Observer<PopuModel>() {
            @Override
            public void onChanged(@Nullable PopuModel popuModel) {
                sort(popuModel);
            }
        });

    }

    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }

    }
    public void showNotice(){
        binding.noticeRl.setVisibility(View.VISIBLE);
    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.content;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 弹出文件夹列表
     */
    protected void openFolder() {

        hideSoftInput();
        if (!isOpen) {
            binding.menuFl.setVisibility(View.VISIBLE);
            if (binding.meunRecyclerview.getHeight() != 0){
                initHeight = binding.meunRecyclerview.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.meunRecyclerview, "translationY",
                    -initHeight, 0).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    binding.meunRecyclerview.setVisibility(View.VISIBLE);
                }
            });
            animator.start();
            isOpen = true;
        }
    }
    protected void setFloder(PopuModel popuModel){
        binding.menu.setText(popuModel.getName());
        isStop = popuModel.getStatus();
    }


    /**
     * 收起文件夹列表
     */
    protected void closeFolder() {

        hideSoftInput();
        if (isOpen) {
            if (binding.meunRecyclerview.getHeight() != 0){
                initHeight = binding.meunRecyclerview.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.meunRecyclerview, "translationY",
                    0,-initHeight).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    binding.meunRecyclerview.setVisibility(View.GONE);
                    binding.menuFl.setVisibility(View.GONE);
                }
            });
            animator.start();
            isOpen = false;
        }
    }
    @Override
    protected void refreshError() {
        super.refreshError();
        viewModel.getGoodsListInfo(isStop,key,true);
//        removeErrorview();

    }


    @Override
    protected Class<MaterialListViewModel> getViewModel() {
        return MaterialListViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material_list;
    }

    public void jump(GoodsDetailResponse response){
//        Intent intent = new Intent(this,MaterialDetailActivity.class);
//        intent.putExtra(Constants.GOODS_CODE,response.getGoodsCode());
//        startActivityForResult(intent,Constants.REFRESH_CODE);
        ARouter.getInstance()
                .build("/materialmanage/materialdetail/materiadetail")
                .withBoolean("isCanEdit",true )
                .withString("goodsCode", response.getGoodsCode())
                .navigation(this,Constants.REFRESH_CODE);

//        MaterialDetailActivity.startActivity(materialListActivity,response.getGoodsCode());
    }


    public void sort(PopuModel popuModel){
        setFloder(popuModel);
        closeFolder();
        Toast.makeText(this,popuModel.getName(),Toast.LENGTH_SHORT).show();
        viewModel.getGoodsListInfo(popuModel.getStatus(),key,true);
    }
}
